package plugins.openform;

import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.form.events.SetFilterEvent;
import kd.bos.list.plugin.AbstractListPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.sdk.plugin.Plugin;

import java.util.ArrayList;
import java.util.EventObject;
import java.util.List;

/**
 * 标准单据列表插件
 */
public class OpenDietPlan extends AbstractListPlugin implements Plugin {
    Object[] names = {};

    @Override
    public void afterCreateNewData(EventObject e) {

        String currentUsername = RequestContext.get().getUserName();
        QFilter filter = new QFilter("dcb4_name", QCP.equals, currentUsername);

        // 查询基础资料dcb4_merchant
        DynamicObject[] dietplanList = BusinessDataServiceHelper.load(
                "dcb4_dietplan",
                "dcb4_name", // 只查询name字段
                new QFilter[]{filter}
        );

        // 提取name字段值
        List<String> nameList = new ArrayList<>();
        for (DynamicObject merchant : dietplanList) {
            nameList.add(merchant.getString("dcb4_name"));
        }
        names = nameList.toArray();

        // this.getView().showTipNotification(currentUsername+"名下的商户记录: " + nameList.size() + "条");

        // 如果当前用户名是"陈旭"（管理员），则显示所有数据
        if (currentUsername.equals("陈旭")) {
            // names = new Object[0];
            // hasMerchant = true; // 标记为有商户记录
        }

        // 如果当前用户名下没有匹配记录，则不显示数据
        if (nameList.isEmpty()) {
            this.getView().showMessage("当前用户没有匹配的商户记录，请联系管理员添加商户信息。");
        }
    }

    @Override
    public void setFilter(SetFilterEvent e) {
        super.setFilter(e);


        if (names != null && names.length > 0) {

            QFilter inFilter = new QFilter("dcb4_name", QCP.in, names);
            e.addCustomQFilter(inFilter);
        } else {
            // 没有饮食计划记录：添加不可能满足的条件（不显示任何数据）
            QFilter impossibleFilter = new QFilter("1", QCP.equals, 2);
            e.addCustomQFilter(impossibleFilter);
        }
    }
}